﻿using System;
using System.ComponentModel;
using System.Diagnostics;

namespace WholeSlideImageViewer
{
    internal abstract class ViewModelBase : INotifyPropertyChanged
    {
        public event PropertyChangedEventHandler? PropertyChanged;

        protected virtual void OnPropertyChanged<T>(string propertyName, ref T valueRef, T value)
        {
            valueRef = value;
            VerifyPropertyName(propertyName);
            PropertyChangedEventHandler? handler = PropertyChanged;
            if (!(handler is null))
            {
                handler(this, new PropertyChangedEventArgs(propertyName));
            }
        }

        protected virtual void OnPropertyChanged(string propertyName)
        {
            VerifyPropertyName(propertyName);
            PropertyChangedEventHandler? handler = PropertyChanged;
            if (!(handler is null))
            {
                handler(this, new PropertyChangedEventArgs(propertyName));
            }
        }

        protected virtual bool ThrowOnInvalidPropertyName => false;

        [Conditional("DEBUG")]
        [DebuggerStepThrough]
        private void VerifyPropertyName(string propertyName)
        {
            if (TypeDescriptor.GetProperties(this)[propertyName] is null)
            {
                string msg = "Invalid property name: " + propertyName;
                if (ThrowOnInvalidPropertyName)
                    throw new Exception(msg);
                else
                    Debug.Fail(msg);
            }
        }
    }
}
